import { Injectable } from '@nestjs/common';
import { getRandomCode } from '@/utils';
import { JwtService } from '@nestjs/jwt';
import { UserService } from '../user/user.service';
import { StudentService } from '../student/student.service';
import * as dayjs from 'dayjs';
import { Result } from '@/common/dto/result.type';
import {
  ACCOUNT_EXIST,
  ACCOUNT_NOT_EXIST,
  CODE_EXPIRED,
  CODE_NOT_EXIST,
  CODE_NOT_EXPIRED,
  LOGIN_ERROR,
  SUCCESS,
  UPDATE_ERROR,
} from '@/common/constants/code';
import { accountAndPwdValidate } from '@/utils';

@Injectable()
export class AuthService {
  constructor(
    private readonly userService: UserService,
    private readonly jwtService: JwtService,
    private readonly studentService: StudentService,
  ) {}
  async sendCodeMsg(tel: string): Promise<Result> {
    const user = await this.userService.findByTel(tel);
    if (user) {
      const diffTime = dayjs().diff(dayjs(user.codeCreateTimeAt));
      if (diffTime < 60 * 1000) {
        return {
          code: CODE_NOT_EXPIRED,
          message: '验证码未过期',
        };
      }
    }
    // const code = getRandomCode();
    // 短信服务个人资质无法申请暂时写死 6666
    const code = '6666';
    // 发送成功之后，看用户是否登录
    if (user) {
      // 更新验证码
      const res = await this.userService.updateCode(user.id, code);
      if (res) {
        return {
          code: SUCCESS,
          message: '验证码发送成功',
        };
      } else {
        return {
          code: UPDATE_ERROR,
          message: '验证码更新失败',
        };
      }
    } else {
      // 用户不存在，创建新用户
      const res = await this.userService.create({
        tel,
        code,
        codeCreateTimeAt: new Date(),
      });
      if (res) {
        return {
          code: SUCCESS,
          message: '验证码发送成功',
        };
      } else {
        return {
          code: UPDATE_ERROR,
          message: '新建账号失败',
        };
      }
    }
  }

  async login(tel: string, code: string): Promise<Result> {
    const user = await this.userService.findByTel(tel);
    if (user) {
      if (!user.codeCreateTimeAt || !user.code) {
        return {
          code: CODE_NOT_EXIST,
          message: '验证码不存在',
        };
      }
      if (code !== user.code) {
        return {
          code: UPDATE_ERROR,
          message: '验证码错误',
        };
      }
      // 验证码不能过期 10分钟过期
      if (dayjs().diff(dayjs(user.codeCreateTimeAt)) > 10 * 60 * 1000) {
        return {
          code: CODE_EXPIRED,
          message: '验证码已过期',
        };
      }
      // 校验验证码是否正确
      if (code === user.code) {
        const token = this.jwtService.sign({
          id: user.id,
        });
        return {
          code: SUCCESS,
          message: '登录成功',
          data: token,
        };
      } else {
        return {
          code: LOGIN_ERROR,
          message: '登录失败，手机号或验证码错误',
        };
      }
    } else {
      return {
        code: ACCOUNT_NOT_EXIST,
        message: '用户不存在',
      };
    }
  }

  async studentLogin(account: string, password: string): Promise<Result> {
    const result = accountAndPwdValidate(account, password);
    if (result.code !== SUCCESS) {
      return result;
    }
    const student = await this.studentService.findByAccount(account);
    if (!student) {
      return {
        code: ACCOUNT_NOT_EXIST,
        message: '用户不存在',
      };
    }
    // 需要对密码进行md5加密
    if (student.password === password) {
      const token = this.jwtService.sign({
        id: student.id,
      });
      return {
        code: SUCCESS,
        message: '登录成功',
        data: token,
      };
    }
    return {
      code: LOGIN_ERROR,
      message: '登录失败，账号或者密码不对',
    };
  }

  async studentRegister(account: string, password: string): Promise<Result> {
    const result = accountAndPwdValidate(account, password);
    if (result.code !== SUCCESS) {
      return result;
    }
    const student = await this.studentService.findByAccount(account);
    if (student) {
      return {
        code: ACCOUNT_EXIST,
        message: '账号已经存在，请使用其他账号',
      };
    }
    const res = await this.studentService.create({
      account,
      password,
    });
    if (res) {
      return {
        code: SUCCESS,
        message: '注册成功',
      };
    }
    return {
      code: UPDATE_ERROR,
      message: '注册失败',
    };
  }
}
